﻿/*

Copyright (c) 2009, Stephen Remde
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY STEPHEN REMDE ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL STEPHEN REMDE BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WikiMiner;
using System.Threading;
using System.Text.RegularExpressions;
using Graphs;

namespace WindowsFormsApplication1
{
    public partial class SearchVisualisation : Form
    {
        float relAdd, relLink;
        Article from, to;

        Graph g;

        public SearchVisualisation(Article from, Article to)
            : this(from, to, 0.8f, 0.7f)
        {

        }

        bool running = true;

        public SearchVisualisation(Article from, Article to, float relAdd, float relLink)
            : this()
        {
            this.from = from;
            this.to=to;
            this.relAdd=relAdd;
            this.relLink = relLink;
            this.g = new Graph();

            Text = string.Format("Starting Search from '{0}' to '{1}'", from.title, to.title);

            ThreadPool.QueueUserWorkItem(new WaitCallback(DoSearch));            
        }

        class WikiVisNode : Node
        {
            public float g;
            public float h;
        }

        class WikiVisLink : Link
        {
            public float rel;
        }


    
        private void DoSearch(object o)
        {            
            var source = from;
            var dest = to;
            
            List<Candidate> open = new List<Candidate>();
            List<Article> closed = new List<Article>();

            open.Add(new Candidate() { article = source, destination = dest, parent = null });
            
            g.AddNode( new WikiVisNode() { 
                    text = source.title, 
                    fixedinplace = true,
                    h = Relatedness.Get(from.title,to.title),
                    x=Width / 2,
                    y=Height / 2
                });

            int its = 0;

            while (open.Count > 0 && running)
            {
                its++;
                
                Candidate at = open.OrderBy(item => item.f).First();

                closed.Add(at.article);
                open.Remove(at);

                Node node_at = g.GetNode(at.article.title);

                node_at.visible = true;

                if (at.parent != null)
                {
                    g.GetLink(node_at, g.GetNode(at.parent.article.title)).visible = true;

                }

                Recolour();

                for (Candidate colour = at; colour != null; colour = colour.parent)
                {
                    g.GetNode(colour.article.title).color = Color.Salmon;
                    if (colour.parent != null)
                    {
                        g.GetLink(
                            g.GetNode(colour.article.title),
                            g.GetNode(colour.parent.article.title)
                            ).color = Color.Salmon;
                    }
                }
                

                //Thread.Sleep(2000);

                if (at.article.title != dest.title)
                {
                    foreach (var link in Links.GetOutLinks(at.article.id, to.id))
                    {
                        float rel = Relatedness.Get(at.article.title, link.title);
                        
                        Node node_to = g.GetNode(link.title);

                        if (node_to == null)
                        {
                            node_to = new WikiVisNode()
                            {
                                text = link.title,
                                visible = false,
                                
                            };
                            g.AddNode(node_to, node_at);
                        }

                        node_to.color = Color.SandyBrown;

                        if (rel > relAdd)
                            node_to.visible = true;

                        Link l = g.AddLink(new WikiVisLink() { 
                            a = node_at, 
                            b = node_to,
                            visible = false, 
                            rel = rel ,
                            text = rel.ToString("0%"),
                            width = 10 * rel,
                            color = Color.SandyBrown
                        });
                        
                        l.AddArrowTo(node_to);
                        
                        if (rel > relLink)
                        {                            
                            l.visible = true;                        
                        }

                        if (!closed.Exists(item => item.id == link.id))
                        {
                            Candidate existing = open.FirstOrDefault(item => item.article.id == link.id);

                            if (existing != null)
                            {
                                existing.UpdateParentIfBetter(at);
                            }
                            else
                            {
                                existing = new Candidate() {
                                    article = link,
                                    parent = at
                                }; 

                                open.Add(existing);
                            }

                            (node_to as WikiVisNode).g = existing.G;
                            (node_to as WikiVisNode).h = existing.H;
                        }
                    }
                }
                else
                {
                    /*
                    List<Article> path = new List<Article>();

                    while (at != null)
                    {
                        path.Add(at.article);
                        at = at.parent;
                    }

                    path.Reverse();
                    //*/
                     
                    break;
                }
            }

            Relatedness.Save();            
        }

 
        class Candidate
        {
            public Article article;
            public Article destination;

            public float G;
            public float H;
            public float f;

            public void Calc()
            {
                H = (1 - Relatedness.Get(article.title, destination.title));
                if (H == 1)
                    H = 1000;

                f = G + H;
            }


            private Candidate _parent = null;

            public Candidate parent
            {
                set
                {
                    _parent = value;

                    if (value == null)
                    {
                        G = 0;
                    }
                    else
                    {
                        G = _parent.G + 1 - Relatedness.Get(article.title, _parent.article.title);
                        destination = parent.destination;
                    }

                    Calc();
                }

                get
                {
                    return _parent;
                }
            }

            internal void UpdateParentIfBetter(Candidate newparent)
            {
                if (_parent != null)
                {
                    if (_parent.G + 1 - Relatedness.Get(article.title, newparent.article.title) < G)
                    {
                        parent = newparent;
                    }
                }
            }
        }

        public SearchVisualisation()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            Refresh();
        }

        private void SearchVisualisation_Paint(object sender, PaintEventArgs e)
        {
            g.Organize(1);
            if (checkBox2.Checked)
            {
                g.AutoAdjustViewport((float)ClientSize.Width, (float)ClientSize.Height, 0.95f,
                    g.GetNodes().Where( n => n.color == Color.Salmon || n.color == Color.SandyBrown )
                    
                    );
            }
            else
            {
                g.AutoAdjustViewport((float)ClientSize.Width, (float)ClientSize.Height, 0.95f);
            }
            g.Draw(e.Graphics, true);
        }

        private void SearchVisualisation_FormClosing(object sender, FormClosingEventArgs e)
        {
            running = false;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            Recolour();
        }


        private void Recolour()
        {
            float maxg = 1;

            if (radioButton1.Checked)
            {
                foreach (var n in g.GetNodes())
                {
                    float t =  (n as WikiVisNode).g ;

                    if (t > maxg)
                        maxg = t;
                }
            }

            foreach (var n in g.GetNodes())
            {
                float t = radioButton1.Checked ? (n as WikiVisNode).g : (n as WikiVisNode).h;
                int gg = (int)(255 * t / maxg);
                if (gg > 255) gg = 255;
                n.color = Color.FromArgb(0, 255 - gg, gg);
            }

            foreach (var l in g.GetLinks())
            {
                l.color = Color.LightBlue;
                if (checkBox1.Checked)
                {
                    l.text = (l as WikiVisLink).rel.ToString("0%");
                }
                else
                {
                    l.text = null;
                }
            }
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            Recolour();
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            Recolour();
        }
    }
}
